package transacciones;

import java.sql.Connection;
import java.sql.SQLException;

public class TransactionDelegate implements TransactionDelegateListener {

	private Connection connection = null;
	private boolean oldStateOfAutoCommit = false;
	private int oldStateOfTransactionIsolation = Connection.TRANSACTION_READ_COMMITTED;
	private TransactionFactory transactionFactory;

	public TransactionDelegate(TransactionFactory parTransactionFactory) {

		transactionFactory = parTransactionFactory;

	}// Fin de TransactionDelegate

	@Override
	public void commit() {
		try {

			this.connection.commit();

		} catch (SQLException e) {
			
			throw new DAOException(e);
			
		}
	} // commit.

	@Override
	public void end() {
		try {

			connection.setAutoCommit(oldStateOfAutoCommit);
			connection.setTransactionIsolation(oldStateOfTransactionIsolation);
			connection.close();

		} catch (SQLException e) {
			
			 throw new DAOException(e);
			 
		}
	} // end.

	@Override
	public void rollback() {
		try {

			this.connection.rollback();

		} catch (SQLException e) {
			
			 throw new DAOException(e);
			 
		}
	} // rollback.

	@Override
	public void start() {
		try {
			if (connection == null) {

				crearNuevoDelegadoTransaccion();

			}// Fin de if(connection == null)
			else if (connection.isClosed()) {

				crearNuevoDelegadoTransaccion();

			}// Fin de if (connection.isClosed())

			if (this.connection.getAutoCommit()) {

				// En caso que la conexion se commite de forma
				// automatica, guardamos el estado anterior e
				// indicamos que no deseamos el commit automatico.
				this.connection.setAutoCommit(false);
				this.oldStateOfAutoCommit = true;

			}// Fin de if (this.connection.getAutoCommit())
		} catch (SQLException e) {
			// throw new DAOException(e);
		}
	} // start.

	/*
	 * Crea un nuevo delegado para las transacciones
	 */
	public void crearNuevoDelegadoTransaccion() {
		try {

			connection = transactionFactory.crearNuevaConeccion("APP");
			oldStateOfTransactionIsolation = connection.getTransactionIsolation();
			connection.setTransactionIsolation(oldStateOfTransactionIsolation);

		} catch (SQLException e) {
			
			throw new DAOException(e);
			
		}

	} // JDBCTransactionDelegateImpl.

	/**
	 * 
	 * Para obtener la coneccion que se creado al momento de registrarNuevo Delegado
	 * @return Connection
	 * 
	 */
	public Connection obtenerConeccion() {

		return connection;

	} // obtenerConeccion.

}// Fin de Clase Principal
